package tma.sdc.batch8.mobile10.shareboard.dao;

import java.sql.Connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

/**
 * This class returns the MySQL database connect object
 * 
 * The method and variable in this class are static to save resources You only
 * need one instance of this class running.
 * 
 * @author anhle
 * 
 */
public class MySQLHelper {

	private static DataSource MySQLShareBoard = null; //hold the database object
	private static Context context = null; //used to lookup the database connection in GlassFish
	
	/**
	 * This is a public method that will return the ShareBoard database connection.
	 * 
	 * @return Database object
	 * @throws Exception
	 */
	private static DataSource mySQLShareBoardConn() throws Exception {
		
		/**
		 * check to see if the database object is already defined...
		 * if it is, then return the connection, no need to look it up again.
		 */
		if (MySQLShareBoard != null) {
			return MySQLShareBoard;
		}
		
		try {
			
			/**
			 * This only needs to run one time to get the database object.
			 * context is used to lookup the database object in GlassFish
			 * MySQLShareBoard will hold the database object
			 */
			if (context == null) {
				context = new InitialContext();
			}
			
			/**
			 * For test database as cloud-bees host
			 */
			MySQLShareBoard = (DataSource) context.lookup("java:comp/env/jdbc/ShareBoard");
			
			/**
			 * For test database as localhost
			 */
//			MySQLShareBoard = (DataSource) context.lookup("ShareBoard");
			
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		return MySQLShareBoard;
		
	}
	
	/**
	 * This method will return the connection to the MySQL ShareBoard schema
	 * Note that the scope is protected which means only java class in the
	 * dao package can use this method.
	 * 
	 * @return Connection to ShareBoard MySQL database.
	 */
	public static Connection getConnection() {
		Connection conn = null;
		try {
			conn = mySQLShareBoardConn().getConnection();
			return conn;
		} 
		catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

}
